//
//  UINavigationBar+ZUtilities.m
//  WeClubs
//
//  Created by Zed Link on 21/4/2017.
//  Copyright © 2017 Zed. All rights reserved.
//

#import "UINavigationBar+ZUtilities.h"
#import <objc/runtime.h>

@implementation UINavigationBar (ZUtilities)

static char overlayKey;
static char emptyImageKey;

- (UIView *)overlay {
    return objc_getAssociatedObject(self, &overlayKey);
}

- (void)setOverlay:(UIView *)overlay {
    objc_setAssociatedObject(self, &overlayKey, overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIImage *)emptyImage {
    return objc_getAssociatedObject(self, &emptyImageKey);
}

- (void)setEmptyImage:(UIImage *)emptyImage {
    objc_setAssociatedObject(self, &emptyImageKey, emptyImage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

#pragma mark - 背景色渐变

- (void)zSetBackgroundColor:(UIColor *)backgroundColor
{
    if (!self.overlay) {
        
        // setShadowImage必须与setBackground: forBarMetrics一起使用才有效果
        
        // 将NavigationBar设置成全透明
        [self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
        // 去除NavigationBar的分割线 (阴影图片)
        [self setShadowImage:[UIImage new]];
        
        // 创建overlay, 用来充当NavigationBar的背景 (覆盖状态栏)
        self.overlay = [[UIView alloc] initWithFrame:CGRectMake(0, -20, [UIScreen mainScreen].bounds.size.width, CGRectGetHeight(self.bounds) + 20)];
        self.overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [self insertSubview:self.overlay atIndex:0];
    }
    
    // 设置背景色
    self.overlay.backgroundColor = backgroundColor;
}

#pragma mark - 导航栏滚动后隐藏

- (void)zSetTranslationY:(CGFloat)translationY
{
    self.transform = CGAffineTransformMakeTranslation(0, translationY);
}

- (void)zSetContentAlpha:(CGFloat)alpha
{
    if ( !self.overlay) {
        [self zSetBackgroundColor:self.barTintColor];
    }
    
    [self setAlpha:alpha forSubviewsOfView:self];
    
    if (alpha == 1) {
        if ( !self.emptyImage) {
            self.emptyImage = [UIImage new];
        }
        self.backIndicatorImage = self.emptyImage;
    }
}

- (void)setAlpha:(CGFloat)alpha forSubviewsOfView:(UIView *)view
{
    for (UIView *subview in view.subviews) {
        if (subview == self.overlay) {
            continue;
        }
        subview.alpha = alpha;
        [self setAlpha:alpha forSubviewsOfView:subview];
    }
}

- (void)zReset
{
    [self setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.overlay removeFromSuperview];
    self.overlay = nil;
}

@end
